package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.BaseContext;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //路径匹配器
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        //1.定义放行的路径
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2.获取uri
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);

        //3.判断uri是否是应该放行的路径
        for (String s : uris) {
            boolean b = antPathMatcher.match(s, requestURI);
            if (b) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //4.判断session内是否有数据
        //4.1 员工后台管理端
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
            log.info("用户已登录，用户名称为：{}", employee.toString());
            Long id = Thread.currentThread().getId();
            log.info("线程id为:{}", id);
            Long empId = employee.getId();
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //4.2 用户登录
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            log.info("用户已登录，用户名称为：{}", user.toString());
            Long id = Thread.currentThread().getId();
            log.info("线程id为:{}", id);
            Long userId = user.getId();
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        log.info("用户未登录");
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);

    }
}